import React, { useEffect, useState } from "react";
import axios from "axios";
import "./style.css";
import { useNavigate } from "react-router-dom";

export interface ItemState {
  title: string;
  tags: {
    tag: string;
  }[];
  name: string;
  city: string;
  count: number;
  id: string;
}

export interface TabState {
  title: string;
  children: ItemState[];
}

const Index = () => {
  const [tab, setTab] = useState<TabState[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeIndex, setActiveIndex] = useState(0);
  const navigate = useNavigate();
  const fetchTab = async () => {
    setLoading(true);
    const resp = await axios.get("/api/tab");
    setTab(resp.data.data);
    setLoading(false);
  };
  useEffect(() => {
    fetchTab();
  }, []);

  if (loading) {
    return <div>...</div>;
  }

  return (
    <div>
      <div>
        <div className="title">
          {tab.map((v, i) => {
            return (
              <span
                key={i}
                className={activeIndex === i ? "active" : ""}
                onClick={() => setActiveIndex(i)}
              >
                {v.title}
              </span>
            );
          })}
        </div>
        <div className="content">
          {tab[activeIndex].children.map((v) => {
            return (
              <dl
                key={v.id}
                onClick={() =>
                  navigate({
                    pathname: "/detail/" + v.id,
                  }, {
										state: v
									})
                }
              >
                <dt>
                  <h3>{v.title}</h3>
                </dt>
                <dd>
                  <p className="tag">
                    {v.tags.map((v, i) => {
                      return <span key={i}>{v.tag}</span>;
                    })}
                  </p>
                  <p>
                    {v.city}--{v.count}人
                  </p>
                  <p>{v.name}</p>
                </dd>
              </dl>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export default Index;
